package com.spring.mvc.mina.server;

import java.net.InetSocketAddress;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.spring.mvc.queue.DispatchQueue;
import com.spring.mvc.queue.DispatchQueueProcessor;
import com.spring.mvc.queue.LinkListQueue;

public class ServerHandler extends IoHandlerAdapter {
	
	private DispatchQueue<QueueInfo> pRecvQueue;
	private MessageProcess[] processer;
	private int queueCount=0;
	
	public ServerHandler() {
		if(queueCount==0){
			queueCount=8;
		}
		this.pRecvQueue=new DispatchQueue<QueueInfo>(new MyRecvQueueProcessor<QueueInfo>(), queueCount, "接收队列");
		this.processer=new MessageProcess[queueCount];
		for (int i = 0; i < queueCount; i++) {
			this.processer[i]=new MessageProcess();
		}
	}
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
		String ip=((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();
		System.out.println("客户端IP："+ip);
	}
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if(!this.pRecvQueue.offer(new QueueInfo(session, message))){
			System.out.println("入队列失败");
		}
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		session.close(false);
	}
	
	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		System.out.println("******************************************");
		/*byte[] buf=new byte[8];
		ByteUtil.write(buf, 0, 0);
		ByteUtil.write(buf, 4, 1);
		session.write(buf);*/
	}
	
	class MyRecvQueueProcessor<T> implements DispatchQueueProcessor<T>{

		public void processQueueElement(LinkListQueue<T> queue, T t,
				int threadId) {
			QueueInfo obj=(QueueInfo)t;
			try{
				ServerHandler.this.processer[threadId].process_message(obj.session,obj.message,threadId);	
			}catch(Exception e){
				e.printStackTrace();
				obj.session=null;
				obj.message=null;
				obj=null;
			}finally{
				obj.session=null;
				obj.message=null;
				obj=null;
			}
		}
	}
	
	class QueueInfo{
		public IoSession session;
		public Object message;
		
		public QueueInfo(IoSession session,Object message) {
			this.session=session;
			this.message=message;
		}
	}
}
